package com.huluobo.a2203kotlindouyindemo.shop

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import androidx.recyclerview.widget.GridLayoutManager
import com.blankj.utilcode.util.ToastUtils
import com.huluobo.a2203kotlindouyindemo.R
import com.huluobo.a2203kotlindouyindemo.adapter.ShopAdapter
import com.huluobo.a2203kotlindouyindemo.cart.CartActivity
import com.huluobo.a2203kotlindouyindemo.databinding.ActivityShopBinding
import com.huluobo.base.bean.GoodsBean
import com.huluobo.base.view.BaseMVVMActivity

class ShopActivity : BaseMVVMActivity<ActivityShopBinding, ShopViewModel>() {
    private lateinit var shopAdapter: ShopAdapter
    private val shopList = mutableListOf<GoodsBean>()
    override fun initData() {
        viewModel.getGoodsList(0, 1, 10)

        viewModel.getGoodsListSuccess.observe(this) {
            if (it.code == 200) {
                shopList.clear()
                shopList.addAll(it.data)
                shopAdapter.notifyDataSetChanged()
            } else {
                ToastUtils.showLong(it.message)
            }
        }

        viewModel.getGoodsListFailed.observe(this) {
            Log.i("TagA", "获取商品列表失败:$it")
        }

        viewModel.addToCartSuccess.observe(this) {
            ToastUtils.showLong(it.message)
        }

        viewModel.addToCartFailed.observe(this) {
            Log.i("TagA", "添加购物车失败:$it")
        }
    }

    override fun initView() {
        dataBinding.shopRv.layoutManager = GridLayoutManager(this, 2)
        shopAdapter = ShopAdapter(shopList)
        dataBinding.shopRv.adapter = shopAdapter

        dataBinding.shopCartFab.setOnClickListener {
            val intent = Intent(this, CartActivity::class.java)
            startActivity(intent)
        }

        shopAdapter.addChildClickViewIds(R.id.item_shop_add_to_cart)
        shopAdapter.setOnItemChildClickListener { adapter, view, position ->
            when (view.id) {
                R.id.item_shop_add_to_cart -> viewModel.addToCart(shopList[position].id, 1)
            }
        }
    }

    override fun getViewModel(): Class<ShopViewModel> {
        return ShopViewModel::class.java
    }

    override fun getLayoutId(): Int = R.layout.activity_shop
}